package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.Base64Utils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.jm.GmUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.UcUuPersoninfo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CQDataServiceImpl implements CQDataService {

    @Autowired
    private JmService jmService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ISealInfoService sealInfoService;

    @Autowired
    private ISealJurService sealJurService;

    @Autowired
    private IBusinessSysService businessSysService;

    @Autowired
    private IPersonService personService;

    @Autowired
    private IUcUuOrginfoService ucUuOrginfoService;

    @Autowired
    private IUcUuPersoninfoService ucUuPersoninfoService;
    //    @Autowired
//    private ISysUserService sysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private BuSysPersonMapper buSysPersonMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SealJurMapper sealJurMapper;
    @Autowired
    private SealDetailMapper sealDetailMapper;


    /**
     * 批量授权手签
     *
     * @return
     */
    @Override
    @Transactional
    public Integer takeSignJur() {
        try {

            //          先清空授权表为手签的数据   循环添加授权数据
            sealJurService.deleteAllSignJurAndTempJurData();

            //          查询所有手签 状态为0
            List<SealInfo> sealInfos = sealInfoService.selectAllSignData();
            if (sealInfos != null && sealInfos.size() > 0) {
                for (SealInfo sealInfo : sealInfos) {
                    SealJur sealJur = new SealJur();
                    sealJur.setState(0L);
                    sealJur.setSealPersonId(sealInfo.getSealDetail().getSealPersonId());
                    sealJur.setSealId(sealInfo.getSealInfoId());
                    sealJur.setJurTime(DateUtils.getTime());
                    sealJur.setJurUserId("1");
                    sealJur.setDueTime("2099-10-01 00:00:00");
                    sealJur.setIsAllowTempJur(1L);
                    sealJur.setIsAlreadyTempJurSeal(0L);
                    sealJur.setSealOrHw(0L);

//                    查找所有的业务系统
                    List<BusinessSys> businessSys = businessSysService.selectBusinessSysList(new BusinessSys());
                    for (BusinessSys businessSy : businessSys) {
                        sealJur.setSealJurId(UUID.fastUUID().toString().replace("-", ""));
                        String sealJurHash = Base64Utils.ESSGetBase64Encode(GmUtil.sm3(sealJur.toString().getBytes()));
                        sealJur.setSafeHash(sealJurHash);
                        sealJur.setBusinessSysIds(businessSy.getbSysId());
                        sealJurMapper.insertSealJur(sealJur);
                    }
                }
            }


            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 3;
        }
    }

    @Override
    public Integer takeCQPersonData() {
        try {
//1.查找用户中心需要同步的全部数据
            List<UcUuPersoninfo> ucUuPersoninfos = ucUuPersoninfoService.selectUcPersonTB();

            if (ucUuPersoninfos != null && ucUuPersoninfos.size() > 0) {

                int countN = 0;
                int countU = 0;
                for (UcUuPersoninfo ucUuPersoninfo : ucUuPersoninfos) {

                    Person personOld = personMapper.selectPersonByPersonId(ucUuPersoninfo.getPersonUuid());

                    if (personOld != null) {
//                        boolean personIdAZ = StringUtils.judgeContainsStr(ucUuPersoninfo.getPersonUuid());
//                        if (!personIdAZ) {

                            /**
                             * 当存在时  判断单位是否有变更  如果有的话将apply_info seal_info  sign_log  的单位字段变更  bu_sys_person新增
                             * 人员编码-外省编号、人员生日 无
                             * 特殊情况为 当单位id为‘sssssssssssssssssO00000000001487’  需要根据 depart_uuid 到org_uuid里查找所属的单位id
                             * 用户换单位时需要将授权表中公章授权删除
                             */
                            BuSysPerson buSysPeople = buSysPersonMapper.selectBusysByPeronId(personOld.getPersonId());
                            if (buSysPeople != null) {

                            } else {
                                BuSysPerson buSysPersonN = new BuSysPerson();
                                buSysPersonN.setState(0);
                                buSysPersonN.setPersonId(personOld.getPersonId());
                                buSysPersonN.setBuPerId(UUID.randomUUID().toString().replace("-", ""));
                                buSysPersonN.setSysId("SYS001");
                                buSysPersonN.setBuSysPerId(personOld.getPersonId());
                                buSysPersonMapper.insertBuSysPerson(buSysPersonN);
                                System.out.println("-------insertbuSysPerson----update--tb-" + countU + "---" + ucUuPersoninfo.getPersonName() + ";" + personOld.getPersonId());
                            }


//               通过personId 在sys_user查找当前人员的所在单位
                            SysUser sysUser = new SysUser();
                            sysUser.setPersonId(personOld.getPersonId());
                            List<SysUser> sysUserList = sysUserMapper.selectUserList(sysUser);

                            if (sysUserList != null && sysUserList.size() > 0) {//有些person表中数据不是sys_user用户
                                SysUser sysUserSys = sysUserList.get(0);
                                Long deptIdSys = sysUserSys.getDeptId();

                                Long depIdUcUU = null;
                                if (!ucUuPersoninfo.getOrgUuid().equals("sssssssssssssssssO00000000001487")) {
                                    SysDept sysDepBySysDPId = sysDeptMapper.selectSysDepBySysDepId(ucUuPersoninfo.getOrgUuid());

                                    depIdUcUU = sysDepBySysDPId.getDeptId();
                                } else {

//                     通过depId查找本系统单位对象
                                    SysDept sysDepBySysDPId = getUnitIdByDepId(ucUuPersoninfo.getDepartUuid());
                                    depIdUcUU = sysDepBySysDPId.getDeptId();
                                }

                                if (deptIdSys != depIdUcUU) {
//                     apply_info seal_info  sign_log 无  的单位字段变更
                                    sysUserSys.setDeptId(depIdUcUU);
                                    sysUserMapper.updateUser(sysUserSys);
                                    System.out.println("-------updatebUsysUser----update--tb-" + countU + "---" + ucUuPersoninfo.getPersonName() + ";" + personOld.getPersonId() + ";" + depIdUcUU);

                                    SealInfo sealInfo = sealInfoService.selectSealByPersonId(personOld.getPersonId());
                                    if (sealInfo != null) {
                                        sealInfo.setUnitId(depIdUcUU + "");
                                        sealInfoService.updateSealInfo(sealInfo);
                                        System.out.println("-------updateSealInfo----update--tb-" + countU + "---" + ucUuPersoninfo.getPersonName() + ";" + personOld.getPersonId() + ";" + depIdUcUU);
                                    }

                                    countU++;
                                }
                            }
//                        } else {
//                            System.out.println("-------updateSealInfo---isExit----Id:" + ucUuPersoninfo.getPersonUuid());
//                        }

                    } else {
                        // 2.循环查找person表对比数据
//            添加person、sys_user、sys_user_role、bu_sys_person 数据  当单位id为‘sssssssssssssssssO00000000001487’  需要根据 depart_uuid 到org_uuid里查找所属的单位id
//             先拼接00000000000000001050000100+登录账号 查找是否存在此信息  存在的话  修改person、sys_user、bu_sys_person、seal_detail、sealjur 人员id数据
//             不存在的话添加数据
                        String personIdQuery = "00000000000000001050000100" + ucUuPersoninfo.getLoginName();

                        Person personQueryIsExit = personMapper.selectPersonByPersonId(personIdQuery);

                        if (personQueryIsExit != null) {
//                            修改person、sys_user、bu_sys_person、seal_detail、sealjur 人员id数据

//                            手动修改   打印日志
                            System.out.println("--------======updateIsExitPersonId=begin======---------------");
                            System.out.println("--------======updateIsExitPersonId=begin======---------------");
                            System.out.println("personIdOld:"+personQueryIsExit.getPersonId()+"；"+"personIdNew:"+ucUuPersoninfo.getPersonUuid());

                            personMapper.updatePersonIdNewUserCenter(personIdQuery,ucUuPersoninfo.getPersonUuid());
                            buSysPersonMapper.updatePersonIdNewUserCenter(personIdQuery,ucUuPersoninfo.getPersonUuid());
                            sysUserMapper.updatePersonIdNewUserCenter(personIdQuery,ucUuPersoninfo.getPersonUuid());
                            sealJurMapper.updatePersonIdNewUserCenter(personIdQuery,ucUuPersoninfo.getPersonUuid());
                            sealDetailMapper.updatePersonIdNewUserCenter(personIdQuery,ucUuPersoninfo.getPersonUuid());


                            System.out.println("--------======updateIsExitPersonId=end=======---------------");
                            System.out.println("--------======updateIsExitPersonId=end=======---------------");

                        } else {
                            Person personNew = new Person();
                            String personIdN = ucUuPersoninfo.getPersonUuid();

                            personNew.setPersonId(ucUuPersoninfo.getPersonUuid());
                            personNew.setPersonId(personIdN);
//        设置人员编码
                            personNew.setEmpNum(ucUuPersoninfo.getPersonUuid());
//        设置登录账号
                            String personNameE = jmService.getEncryptString(ucUuPersoninfo.getPersonName());
                            personNew.setLoginAccount(personNameE);
                            personNew.setPersonName(personNameE);
//       设置状态
                            personNew.setState(0L);
                            personNew.setSex(Long.valueOf(ucUuPersoninfo.getGenderScode()));
                            if (ucUuPersoninfo.getBirthDate() != null && !"".equals(ucUuPersoninfo.getBirthDate())) {
                                personNew.setBirNum(jmService.getEncryptString(ucUuPersoninfo.getBirthDate().replace("-", "")));
                            } else {
                                personNew.setBirNum("9vnbplfGp9CJgWrMxy4MCjgAAAAAAAAAAAAAAAAAAAA=");
                            }
                            personNew.setProvincialUserId(jmService.getEncryptString(ucUuPersoninfo.getPersonCode()));
                            personNew.setLoginAccount(personNameE);
                            personNew.setLoginPsw("S5FFeBg7gCpjozvvO5/FG5Dv19xx20RqY0Xo6U5RD3wnWVRK9Ap9gHre+f/9d8YzbSBK8R9b+nTQ0+FWEbKFVTYwAAAAAAAAAAAAAAAAAAA=");

                            personMapper.insertPerson(personNew);
                            System.out.println("-------insertPerson----new--tb-" + countN + "----" + ucUuPersoninfo.getPersonName() + ";" + personIdN);

                            SysUser sysUser = new SysUser();
                            sysUser.setPersonId(personIdN);
//                 sysUser.setUserType("00");
                            sysUser.setStatus("0");
                            sysUser.setDelFlag("0");
                            sysUser.setCreateBy("admin");
                            sysUser.setPassword("");
                            sysUser.setRemark("签章人");
                            Long[] roleIds = {103L};
                            sysUser.setRoleIds(roleIds);
//                单位id查找 当单位id为‘sssssssssssssssssO00000000001487’  需要根据 depart_uuid 到org_uuid里查找所属的单位id

                            if (!ucUuPersoninfo.getOrgUuid().equals("sssssssssssssssssO00000000001487")) {
                                SysDept sysDepBySysDPId = sysDeptMapper.selectSysDepBySysDepId(ucUuPersoninfo.getOrgUuid());
                                sysUser.setDeptId(Long.valueOf(sysDepBySysDPId.getDeptId()));
                            } else {

//                     通过depId查找本系统单位对象
                                SysDept sysDepBySysDPId = getUnitIdByDepId(ucUuPersoninfo.getDepartUuid());
                                sysUser.setDeptId(Long.valueOf(sysDepBySysDPId.getDeptId()));

                            }

                            sysUser.setUserName(personNameE);
                            sysUser.setNickName(personNameE);
                            sysUserMapper.insertUser(sysUser);
                            System.out.println("-------insertsysUser----new--tb-" + countN + "----" + ucUuPersoninfo.getPersonName() + ";" + personIdN);

                            // 新增用户与角色管理
                            List<SysUserRole> list = new ArrayList<SysUserRole>();
                            SysUserRole ur = new SysUserRole();
                            ur.setUserId(sysUser.getUserId());
                            ur.setRoleId(103L);
                            list.add(ur);
                            userRoleMapper.batchUserRole(list);
                            System.out.println("-------insertsysUserRole----new--tb-" + countN + "----" + ucUuPersoninfo.getPersonName() + ";" + personIdN);


                            BuSysPerson buSysPerson = new BuSysPerson();
                            buSysPerson.setState(0);
                            buSysPerson.setPersonId(personIdN);
                            buSysPerson.setBuPerId(UUID.randomUUID().toString().replace("-", ""));
                            buSysPerson.setSysId("SYS001");
                            buSysPerson.setBuSysPerId(personIdN);
                            buSysPersonMapper.insertBuSysPerson(buSysPerson);
                            System.out.println("-------insertbuSysPerson----new--tb-" + countN + "---" + ucUuPersoninfo.getPersonName() + ";" + personIdN);

                            countN++;

                        }

                    }


                }


            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 3;
        }
    }

    //    通过用户中心depId查找本系统单位对象
    private SysDept getUnitIdByDepId(String departUuid) {

        UcUuOrginfo ucUuOrginfo = ucUuOrginfoService.selectUcUuOrginfoByOrgUuid(departUuid);

        SysDept sysDept = sysDeptMapper.selectSysDepBySysDepId(ucUuOrginfo.getParentUuid());

        if (!sysDept.getTypeCode().equals("1")) {

            getUnitIdByDepId(sysDept.getSysDepId());
        }
        return sysDept;
    }


    @Override
    public Integer takeCQOrgInfo() {
        try {
//            1.查找用户中心所有非虚拟组织、未删除  orginfo集合
            UcUuOrginfo ucUuOrginfo = new UcUuOrginfo();
            ucUuOrginfo.setSysisdelete("0");
            ucUuOrginfo.setIsVirtualOrg("0");
            List<UcUuOrginfo> ucUuOrginfos = ucUuOrginfoService.selectUcUuOrginfoList(ucUuOrginfo);

//            2.循环orginfo集合 通过org_uuid 查找sys_dept表
            if (ucUuOrginfos != null && ucUuOrginfos.size() > 0) {
                for (UcUuOrginfo uuOrginfo : ucUuOrginfos) {
                    //                    通过org_uuid 在sys_dept中查找
                    SysDept sysDept = sysDeptMapper.selectSysDepBySysDepId(uuOrginfo.getOrgUuid());
                        //单位
                    if (uuOrginfo.getOrgTypeScode().equals("1")) {
                        if (sysDept != null) {
//                    当存在时判断单位名称、单位编码、修改时间 和 上级单位id 进行判断修改



                        } else {
//                    当不存在时进行添加


                        }
                    } else {
                        //部门
                        if (sysDept != null) {
//                    当存在时判断单位名称、单位编码、修改时间 和 上级单位id 进行判断修改



                        } else {
//                    当不存在时进行添加


                        }


                    }


                }
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 3;
        }
    }

    /**
     * 自动将person表转换业务系统人员数据
     *
     * @return
     */
    @Override
    public Integer takeBuSysPersonData() {

        try {
//        1.查找所有person表数据
            List<Person> persons = personService.selectPersonList(new Person());
            if (persons != null && persons.size() > 0) {
                for (Person person : persons) {
//        2.根据person_id循环判断busysperson表是否有对应的数据  没有话添加
                    BuSysPerson buSysPeople = buSysPersonMapper.selectBusysByPeronId(person.getPersonId());
                    if (buSysPeople != null) {

                    } else {
                        BuSysPerson buSysPersonN = new BuSysPerson();
                        buSysPersonN.setState(0);
                        buSysPersonN.setPersonId(person.getPersonId());
                        buSysPersonN.setBuPerId(UUID.randomUUID().toString().replace("-", ""));
                        buSysPersonN.setSysId("SYS001");
                        buSysPersonN.setBuSysPerId(person.getPersonId());
                        buSysPersonMapper.insertBuSysPerson(buSysPersonN);
                        System.out.println("-------buSysPersonService----new--onlyTake" + person.getPersonId());
                    }
                }
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 3;
        }
    }
}
